<template>
  <div class="select-personnel">
    <je-grid
      ref="grid"
      border
      auto-resize
      show-overflow="ellipsis"
      keep-source
      show-header-overflow
      class="select-personnel-grid"
      resizable
      height="300"
      size="mini"
      header-align="center"
      :edit-config="{
        trigger: 'click',
        mode: 'cell',
        showStatus: true,
        showInsertStatus: false,
      }"
      :store="gridStore"
    >
      <je-column width="40" align="center">
        <template #header>
          <i style="font-size: 16px; cursor: pointer" class="fal fa-plus" @click="addColumn"></i>
        </template>
        <template #default="{ row }">
          <i
            style="font-size: 16px; cursor: pointer"
            class="fal fa-times"
            @click="deleteColumn(row)"
          ></i>
        </template>
      </je-column>
      <je-column
        field="name"
        :title="$t('SelectPersonnel.id')"
        width="120"
        :edit-render="inputRender"
      >
        <template #edit="{ row }">
          <je-select
            v-model:value="row.type"
            :get-popup-container="getPopupContainer"
            config-info="JE_WF_TARGERTYPE,type~name,code~text,s"
            @change="clearData(row, true)"
          />
        </template>
      </je-column>
      <je-column
        field="resourceName"
        :title="$t('SelectPersonnel.code')"
        :edit-render="inputRender"
      >
        <template #edit="{ row }">
          <je-select-user
            v-if="row.type == 'userConfig'"
            v-model:value="row.resourceName"
            config-info=",resourceCode~resourceName~resourceId,code~text~id,M"
          />
          <je-select-grid
            v-else-if="row.type == 'formFieldConfig'"
            v-model:value="row.resourceName"
            config-info="JE_CORE_RESOURCEFIELD,resourceCode~resourceName~resourceId,RESOURCEFIELD_CODE~RESOURCEFIELD_NAME~JE_CORE_RESOURCEFIELD_ID,M"
            :querys="[
              { code: 'RESOURCEFIELD_FUNCINFO_ID', type: '=', value: funcInfo.funcId, cn: 'and' },
              {
                code: 'RESOURCEFIELD_XTYPE',
                type: 'notIn',
                value: ['fieldset', 'child', 'childfuncfield', 'displayfield'],
                cn: 'and',
              },
            ]"
          />
          <je-select-tree
            v-else-if="row.type == 'specialConfig'"
            v-model:value="row.resourceName"
            config-info="JE_WF_SPECIALASSGINE,resourceCode~resourceName~resourceId,code~text~id,M"
          />
          <je-input
            v-else-if="['customConfig', 'businessSqlAssignmentConfig'].indexOf(row.type) != -1"
            v-model:value.trim="row.resourceName"
            readonly
            @change="clearData(row)"
          >
            <template #suffix>
              <i style="cursor: pointer" class="fas fa-list-ul" @click="handlerModal(row)"></i>
            </template>
          </je-input>
          <je-input
            v-else-if="['roleConfig', 'departmentConfig', 'positionConfig'].indexOf(row.type) != -1"
            v-model:value.trim="row.resourceName"
            readonly
            @change="clearData(row)"
          >
            <template #suffix>
              <i style="cursor: pointer" class="fas fa-list-ul" @click="handlerModal(row)"></i>
            </template>
          </je-input>
          <je-input
            v-else-if="['rbacSqlAssignmentConfig'].indexOf(row.type) != -1"
            v-model:value="row.resourceName"
          >
            <template #suffix>
              <i style="cursor: pointer" class="fas fa-list-ul" @click="handlerModal(row)"></i>
            </template>
          </je-input>
        </template>
      </je-column>
      <je-column field="entryPath" :edit-render="inputRender" width="150">
        <template #header>
          <i class="conditionicon fas fa-question-circle" @click="clickIcon('entryPath')"></i>
          {{ $t('SelectPersonnel.source') }}
        </template>
        <template #edit="{ row }">
          <je-select v-model:value="row.entryPath" :options="sourceOptions" />
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.entryPath, sourceOptions) }}
        </template>
      </je-column>
    </je-grid>

    <je-form-item name="referToCode" style="margin-top: 16px; padding-right: 16px">
      <template #label>
        <i class="conditionicon fas fa-question-circle" @click="clickIcon('referToCode')"></i>
        {{ $t('SelectPersonnel.personnelReference') }}
      </template>
      <je-select
        v-model:value="formState.referToCode"
        v-model:model="formState"
        config-info="JE_WF_ASSGINETYPE,referToCode,code,S"
      />
    </je-form-item>

    <ServeConfiguration
      v-if="serveConfiguration"
      :checked-row="checkedRow"
      @setModalType="setModalType"
      @closeModal="closeModal"
    />
    <SqlConfiguration
      v-if="sqlConfiguration"
      :checked-row="checkedRow"
      :func-info="funcInfo"
      @setModalType="setModalType"
      @closeModal="closeModal"
    />
    <RoledeptpostSelector
      v-if="SelectorType"
      :checked-row="checkedRow"
      :func-info="funcInfo"
      @setModalType="setModalType"
    />
    <Explain
      v-if="explainType"
      :modal-context="modalContext"
      width="400px"
      @closEexplain="closEexplain"
    />
    <SqlDefinition
      v-if="sqlDefinition"
      :checked-row="checkedRow"
      @setModalType="setModalType"
      @closeModal="closeModal"
    />
  </div>
</template>

<script>
  import { defineComponent, ref, watch } from 'vue';
  import { Grid, Input, Select, Form, InputSelect, Data, Modal } from '@jecloud/ui';
  import { inputRender } from '@/helper/edit-render';
  import { isNotEmpty } from '@jecloud/utils';

  import ServeConfiguration from './modal/serve-configuration.vue';
  import SqlConfiguration from './modal/sql-configuration.vue';
  import RoledeptpostSelector from './modal/roledeptpost-selector.vue';
  import Explain from '@/components/explain/index.vue';
  import SqlDefinition from './modal/sql-definition.vue';

  export default defineComponent({
    name: 'SelectPersonnel',
    components: {
      JeGrid: Grid,
      JeColumn: Grid.Column,
      JeInput: Input,
      JeSelect: Select,
      JeFormItem: Form.Item,
      JeSelectGrid: InputSelect.Grid,
      JeSelectTree: InputSelect.Tree,
      JeSelectUser: InputSelect.User,
      ServeConfiguration,
      SqlConfiguration,
      RoledeptpostSelector,
      Explain,
      SqlDefinition,
    },
    props: {
      funcInfo: {
        type: Object,
        default: () => {
          return {};
        },
      },
      assignmentConfig: {
        type: Object,
        default: () => {
          return {};
        },
      },
      nodeId: {
        type: String,
        default: '',
      },
      wfEditor: {
        type: Object,
        default: () => {
          return {};
        },
      },
      nodeType: {
        type: String,
        default: '',
      },
    },
    setup(props) {
      const grid = ref(null);
      const formState = ref(props.assignmentConfig);

      //列表的数据源store
      const gridStore = Data.Store.useGridStore({
        data: props.assignmentConfig.resource,
      });

      const SelectorType = ref(false);

      //进入节点的数据
      const sourceOptions = ref([{ value: 'S1', label: '111' }]);

      //获得改节点的上级节点 组装成进入路径下拉框的数据
      const getSourceNodes = ($editor) => {
        const datas = [];
        if ($editor) {
          const selectNode = $editor.graph.getSelectionCell();
          if (selectNode && selectNode.edges && selectNode.edges.length > 0) {
            selectNode.edges.forEach((edge) => {
              const target = edge.target;
              //如果线的出口是本节点的话,那么这个线就是本节的入线
              if (target) {
                if (target.getId() == selectNode.getId()) {
                  const source = edge.source;
                  //这个线的入口节点就是 本节的上一个节点 (去掉分支聚合)
                  if (
                    source &&
                    ['branchGateway', 'aggregationGateway'].indexOf(source.getAttribute('type')) ==
                      -1
                  ) {
                    const name = source.getAttribute('label') || source.getAttribute('name');
                    const id = source.getId();
                    datas.push({ value: id, label: name });
                  }
                }
              }
            });
          }
        }
        sourceOptions.value = datas;
      };

      //监听节点Id刷新数据
      watch(
        () => props.nodeId,
        () => {
          gridStore.loadData(props.assignmentConfig.resource);
          formState.value = props.assignmentConfig;
          const $editor = props.wfEditor.editor.$editor;
          getSourceNodes($editor);
        },
        { immediate: true },
      );

      //添加列
      const addColumn = () => {
        const data = {
          entryPath: '',
          type: '',
          name: '',
          resourceName: '',
          resourceCode: '',
          resourceId: '',
        };
        gridStore.insert(data, -1);
      };

      //删除列
      const deleteColumn = (row) => {
        gridStore.remove(row);
      };

      //点击icon弹出弹窗 ['DIY', 'USERSQL'].indexOf(row.id)
      const checkedRow = ref({});
      const serveConfiguration = ref(false);
      const sqlConfiguration = ref(false);
      const sqlDefinition = ref(false);
      const handlerModal = (row) => {
        checkedRow.value = row;
        if (row.type == 'customConfig') {
          serveConfiguration.value = true;
        } else if (row.type == 'businessSqlAssignmentConfig') {
          sqlConfiguration.value = true;
        } else if (['roleConfig', 'departmentConfig', 'positionConfig'].indexOf(row.type) != -1) {
          SelectorType.value = true;
        } else if (row.type == 'rbacSqlAssignmentConfig') {
          sqlDefinition.value = true;
        }
      };

      const closeModal = ({ type, modalType }) => {
        if (modalType == 'sql') {
          sqlConfiguration.value = false;
        } else if (modalType == 'SqlConfiguration') {
          sqlDefinition.value = false;
        } else {
          serveConfiguration.value = false;
        }
      };

      //弹窗关系重置SelectorType = false
      const setModalType = ({ type, btnType, data }) => {
        //如果是选择部门加色岗位
        if (type == 'RoledeptpostSelector') {
          if (btnType == 'save') {
            //checkedRow.value = data.
            const selectData = data.selectData;
            if (selectData && selectData.length > 0) {
              //根据选中的数据给列表对应的字段赋值
              const resourceCode = [],
                resourceId = [],
                resourceName = [],
                resourceIcon = [];
              selectData.forEach((item) => {
                resourceCode.push(item.resourceCode);
                resourceId.push(item.resourceId);
                resourceName.push(item.resourceName);
                resourceIcon.push(item.resourceIcon);
              });
              checkedRow.value.resourceCode = resourceCode.join(',');
              checkedRow.value.resourceId = resourceId.join(',');
              checkedRow.value.resourceName = resourceName.join(',');
              checkedRow.value.resourceIcon = resourceIcon.join(',');
            }
            //权限赋值
            checkedRow.value.permission = data.permission;
          }
          SelectorType.value = false;
        }
        //如果是用户SQL
        if (type == 'SqlConfiguration') {
          checkedRow.value.resourceName = data.sql;
          checkedRow.value.sql = data.sql;
        }
        //如果是自定义
        if (type == 'ServeConfiguration') {
          checkedRow.value.resourceName = data.serviceName;
          checkedRow.value.serviceName = data.serviceName;
          checkedRow.value.methodName = data.methodName;
        }
        //如果是S定义QL定义
        if (type == 'SqlConfiguration') {
          checkedRow.value.resourceName = data.sql;
          checkedRow.value.sql = data.sql;
        }
      };

      watch(
        () => gridStore.data,
        (newVal) => {
          const datas = [];
          newVal.forEach((item) => {
            if (isNotEmpty(item.name)) {
              datas.push(item);
            }
          });
          formState.value.resource = datas;
        },
        { deep: true },
      );

      //清空数据
      const clearData = (row, type) => {
        row.resourceCode = '';
        row.resourceId = '';
        row.resourceName = '';
        row.resourceIcon = '';
        row.permission = {};
        row.sql = '';
        row.serviceName = '';
        row.methodName = '';
        if (row.type == 'orgTreeConfig' && type) {
          const length = gridStore.data.filter((item) => {
            return item.type == 'orgTreeConfig';
          }).length;
          if (length > 1) {
            gridStore.remove(row);
            Modal.alert('只能选择一个组织架构！', 'warning');
          }
        }
      };

      //列表单元格格式化
      const getSelectLabel = (value, list, valueProp = 'value', labelField = 'label') => {
        const item = list.find((item) => item[valueProp] === value);
        return item ? item[labelField] : null;
      };

      const getPopupContainer = () => {
        return document.body;
      };

      //点击icon
      const modalContext = ref('');
      const explainType = ref(false);
      const clickIcon = (type) => {
        if (type == 'entryPath') {
          modalContext.value =
            '进入路径只可以选择前置连线进入的节点，为不同的来源路径设置不同的可处理人规则。';
        }
        if (type == 'referToCode') {
          modalContext.value =
            '人员参照是指：当可处理人选择“特殊处理”，并且规则值为“直属领导”、“本部门领导”、“本部门监管领导”、“本部门内人员”、“本部门内(含子)人员”、“监管部门内人员”选项时，选择的人员参照为“当前登录人”或是“流程启动人”时才生效。';
        }
        explainType.value = true;
      };
      //弹窗关闭回调
      const closEexplain = () => {
        explainType.value = false;
      };

      return {
        addColumn,
        deleteColumn,
        inputRender,
        formState,
        checkedRow,
        handlerModal,
        serveConfiguration,
        sqlConfiguration,
        grid,
        SelectorType,
        setModalType,
        clearData,
        sourceOptions,
        getSourceNodes,
        getSelectLabel,
        gridStore,
        closeModal,
        getPopupContainer,
        clickIcon,
        closEexplain,
        explainType,
        modalContext,
        sqlDefinition,
      };
    },
  });
</script>

<style lang="less" scoped></style>

<style lang="less">
  .select-personnel {
    .select-personnel-grid {
      .vxe-table--render-default .vxe-table--border-line {
        border-left: 0 !important;
        border-top: 0 !important;
      }
    }
  }
</style>
